package com.five.api.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.five.controller.BaseController;
import com.five.entity.User;
import com.five.exceptions.BusinessException;
import com.five.util.MySessionContext;
import com.five.util.SmsInterfaceUtil;
import com.five.util.VCGenerateUtil;
import com.five.vo.BaseResultVO;
import com.five.api.service.UserService;
import com.mysql.cj.jdbc.MysqlDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author: star
 * @Date: 2021-05-18 20:05
 * UserController 测试
 */
@Controller
@RequestMapping("user")
@Api(tags = "用户业务接口")
@CrossOrigin
public class UserController extends BaseController {


    @Autowired
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(UserController.class);


    @ResponseBody
    @RequestMapping(value = "code",method = RequestMethod.GET)
    @ApiOperation("验证码接口")
    public BaseResultVO SendVerificationCode(@ApiParam(value = "手机号") String telephone,HttpServletRequest request){

        //获取验证码
        String verificationCode = VCGenerateUtil.generateCode();

        //将验证码存储到session中
        HttpSession session = request.getSession();
        session.setAttribute("verificationCode",verificationCode);


        logger.info("SMS  telephone:{} VerificationCode:{}",telephone,verificationCode);
        //调用发送短信接口
        boolean b = VCGenerateUtil.sendSmsCode(telephone, verificationCode);

        if (b==true){
            //返回ture代表短信发送成功
            return successResp(session.getAttribute("verificationCode"));
        }else {

            return errorResp("发送失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ApiOperation("注册接口")
    @CrossOrigin
    public BaseResultVO<User> register(@ApiParam(value = "用户对象") User user,HttpServletRequest request, @ApiParam(value = "验证码") String code) {
//        logger.info("login userName:{} password:{} code:{}",user.getTelephone(),user.getPassword(),code);
//        ServletContext servletContext = request.getServletContext();
//        String validationCode = (String) servletContext.getAttribute("validationCode");

        //获取session中的验证码
        HttpSession session = request.getSession();
        Object verificationCode = session.getAttribute("verificationCode");
        System.out.println(verificationCode);
        //进行比较
        if (code==null||"".equals(code)){
            return errorResp("请输入验证码");

        }
        if (verificationCode.equals(code)){
            User dbUser = userService.selectUserByRegister(user.getTelephone());
            if (dbUser==null){
                int i = userService.insUser(user);
                return successResp("注册成功,请前往登录页");
            }else {
                throw new BusinessException("手机号已被注册");
            }
        }else {
            return errorResp("验证码错误");
        }
    }
    @ResponseBody
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ApiOperation("登录接口")
    @CrossOrigin(allowCredentials = "true",originPatterns = "*")
    public BaseResultVO<User> login(@ApiParam(value = "用户对象")User user,HttpServletRequest request){
        logger.info("login userName:{} password:{}",user.getTelephone(),user.getPassword());
//        User dbUser = userService.selectUserByLogin(user);
//        //将用户信息存进session
//        MySessionContext mySC = MySessionContext.getInstance();
//        HttpSession session = request.getSession();
//        session.setAttribute( "User",dbUser);
//        mySC.addSession(session);


        UsernamePasswordToken token = new UsernamePasswordToken(user.getTelephone().toString(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            //调用Shiro 进行登录校验
            subject.login(token);
        } catch (UnknownAccountException e) {
            logger.error(e.getMessage());
            return errorResp("用户名不存在");
        } catch (IncorrectCredentialsException e) {
            logger.error(e.getMessage());
            return errorResp("密码错误");
        }


        logger.info("login end");

        //获取登录后的用户信息
        User sessionUser = (User) SecurityUtils.getSubject().getPrincipal();

        return successResp(sessionUser);
    }

    @ResponseBody
    @RequestMapping(value = "showSession",method = RequestMethod.POST)
    @ApiOperation("获取用户session")
    public  BaseResultVO showSession(){
        Object dbUser = SecurityUtils.getSubject().getPrincipal();

        return successResp(dbUser);
    }

    @ResponseBody
    @RequestMapping(value = "updateUser",method = RequestMethod.POST)
    @ApiOperation("修改个人信息接口")
    public BaseResultVO<User> updateUser(@ApiParam(value = "用户对象") User user){
        logger.info("修改个人信息user: "+user);
        int i = userService.updateUser(user);
        if(i > 0){
            return successResp("修改成功");
        }else{
            return errorResp("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "selectUsers",method = RequestMethod.GET)
    @ApiOperation("查询用户信息列表接口")
    public BaseResultVO<User> selectUsers(){
        List<User> users = userService.selectUsers();
        logger.info("查询用户信息列表："+users);
        if(users != null){
            return successResp(users);
        }else{
            return errorResp("查询失败");
        }
    }

    @PostMapping(value = "/upload", consumes = "multipart/*",
            headers = "content-type=multipart/form-data")
    @ApiOperation(value = "用户头像上传")
    @ResponseBody
    public BaseResultVO upload(@ApiParam(value="文件") MultipartFile file,@ApiParam(value = "用户id") @Param("id") Long id) {
        System.out.println(file);
        System.out.println(id);
        if (file.isEmpty()) {
            throw new RuntimeException("文件上传失败");
        }
        // 获取根目录
        String courseFile = System.getProperty("user.dir");
        System.out.println(courseFile);
        // 获取父项目的路径
        File localFile = new File(courseFile);
        String local = "view/img/user/";
//        String parent = localFile.getParent()+"/webapps/" + local;
        String parent = "E:/install/apache-tomcat-9.0.40/webapps/" + local;

        String imgUrl ="http://localhost:8080/"+ local +id+"-"+file.getOriginalFilename();
        System.out.println(imgUrl);
        // 图片保存的路径
        String filePath = parent +id+"-"+file.getOriginalFilename();
        File saveFile = new File(filePath);
        System.out.println(filePath);
        try {
            //使用transferTo(dest)方法将上传文件写到服务器上指定的文件;
            //
            //原因文件流只可以接收读取一次，传输完毕则关闭流;
            file.transferTo(saveFile);
            System.out.println("用户id" + id);
            logger.info("id："+id+"的用户上传了头像。");
            userService.UpdateUserUpload(imgUrl,id);
        } catch (IOException e) {
            System.out.println("出错了");
            e.printStackTrace();
            throw new BusinessException("文件上传失败,请重新上传");
        }
        return successResp(imgUrl);
    }


    @PostMapping(value = "/selectUserBalance")
    @ApiOperation(value = "根据id查询用户钱包余额")
    @ResponseBody
    public BaseResultVO selectUserBalance(@ApiParam("用户对象") User user){

        System.out.println(user);

        if (user == null){
           return errorResp("用户id为空");
        }

        BigDecimal bigDecimal = userService.selectUserBalance(user.getId());
        return  successResp(bigDecimal);
    }

    @GetMapping(value = "/loginOut")
    @ApiOperation(value = "用户退出接口")
    @ResponseBody
    public void selectUserBalance(HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println("session对象："+session);
        // 创建保存session的工具类对象
        MySessionContext instance = MySessionContext.getInstance();
        // 用户退出删除session
        instance.delSession(session);
        logger.info("用户退出---session对象="+session);
    }

}
